package com.mofeng.myshop.service.fileupload.impl;

import com.mofeng.myshop.exception.MyException;
import com.mofeng.myshop.service.fileupload.FileServer;
import com.mofeng.myshop.until.Constants;
import com.mofeng.myshop.until.MyUtil;
import com.mofeng.myshop.until.ServletUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * 文件上传，本地实现
 */
@Service(Constants.Settings.FILE_UPLOAD_TYPE + "local")
@Slf4j
public class FileLocalServerImpl implements FileServer {

    /**
     * 添加文件
     *
     * @param multipartFile 文件
     * @param pathPrefix    文件的基础存储路径
     * @param id            文件的id
     * @return {文件URL，文件的实际物理地址}
     */
    @Override
    public String[] saveFile(MultipartFile multipartFile, String pathPrefix, String id) {
        try {
            //创建图片的保存目录（保存规则:配置目录 日期 类型 ID.类型)
            String fileType = MyUtil.FileUtil.getFileType(multipartFile, defaultImageType);
            long currentTimeMillis = System.currentTimeMillis();
            String currentDay = MyUtil.DateUtil.getTimeStr(currentTimeMillis, "yyyy_MM_dd");
            String dayPath = pathPrefix + currentDay;
            String newPath = dayPath + File.separator + fileType;
            String fileName = id + "." + fileType;
            MyUtil.FileUtil.checkAndCreateDirectory(newPath);
            String path = newPath + File.separator + fileName;
            String url = currentTimeMillis + "_" + id + "." + fileType;
            multipartFile.transferTo(new File(path));

//            //压缩
//            String originalPath = newPath + File.separator + id + "-p." + fileType;
//            try {
//                MyUtil.FileUtil.copyFile(path, originalPath);
//                MyUtil.ImageUtil.compressImage(new File(originalPath), new File(path), fileType, 0.1F);
//            } catch (Exception e) {
//                MyUtil.FileUtil.copyFile(path, originalPath);
//                log.error("压缩出现问题：" + e.getMessage());
//            }

            String urlPrefix = "/_api/portal/image/";
            return new String[]{urlPrefix + url, path};
        } catch (Exception e) {
            throw new RuntimeException("文件存储发生错误", e);
        }
    }

    /**
     * 删除文件
     *
     * @param basePath 文件基础路径
     * @param url      文件路径
     */
    @Override
    public String delFile(String basePath, String url) {
        try {
            String[] file = parseFilePath(basePath, url);
            new File(file[0]).delete();
            return file[1];
        } catch (Exception e) {
            throw new RuntimeException("图片删除失败，请检查重试~");
        }
    }

    /**
     * 解析路径
     *
     * @param url 文件路径
     * @return 返回文件路径的关键字
     */
    @Override
    public String parseFileId(String url) {
        return parseFilePath("", url)[1];
    }

    /**
     * 获取文件
     *
     * @param url 文件路径
     */
    @Override
    public void getFile(String basePath, String url) {
        try {
            String imagesPath = parseFilePath(basePath, url)[0];
            HttpServletResponse response = ServletUtils.getResponse();
            try (OutputStream writer = response.getOutputStream();
                 FileInputStream fis = new FileInputStream(imagesPath)) {
                // 读取文件内容到字节数组
                byte[] fileBytes = new byte[1024];
                response.setContentType("image/png");
                while (fis.read(fileBytes) != -1) {
                    writer.write(fileBytes);
                }
                writer.flush();
            } catch (NullPointerException e) {
                MyUtil.ErrorUtil.printError(e);
            }
        } catch (Exception e) {
            throw new MyException("图片获取失败", e);
        }
    }

    /**
     * 解析文件路径
     *
     * @param basePath 基础路径
     * @param url      URL
     * @return 文件物理地址
     */
    private String[] parseFilePath(String basePath, String url) {
        String[] path = url.split("_");
        String dayValue;
        dayValue = MyUtil.DateUtil.getTimeStr(Long.parseLong(path[0]), "yyyy_MM_dd");
        String name = path[1];
        String type = name.split("\\.")[1];
        String id = name.replace(type, "").replace(".", "");
        String filePath = new StringBuffer(basePath)
                .append(dayValue).append(File.separator)
                .append(type).append(File.separator)
                .append(name).toString();
        return new String[]{filePath, id};
    }
}
